package com.flybutter.usagelab.ui

import android.app.PendingIntent
import android.app.usage.UsageStatsManager
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.widget.ImageView
import android.widget.RemoteViews
import com.flybutter.usagelab.R
import com.flybutter.usagelab.broadcast.CUSTOM_INTENT_ACTION_WIDGET_EVENT
import com.flybutter.usagelab.utils.getAppIcon
import com.flybutter.usagelab.utils.getInstalledPackage
import java.time.LocalDateTime
import java.time.ZoneId

/**
 * Implementation of App Widget functionality.
 */
class PredictAppWidget : AppWidgetProvider() {
    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray
    ) {
        // There may be multiple widgets active, so update all of them
        for (appWidgetId in appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId)
        }
    }

    override fun onEnabled(context: Context) {
        // Enter relevant functionality for when the first widget is created
    }

    override fun onDisabled(context: Context) {
        // Enter relevant functionality for when the last widget is disabled
    }
}

internal fun updateAppWidget(
    context: Context,
    appWidgetManager: AppWidgetManager,
    appWidgetId: Int
) {
    val pm = context.packageManager
    // Construct the RemoteViews object
    val views = RemoteViews(context.packageName, R.layout.predict_app_widget)

    val sm = context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
    val start = LocalDateTime.now().minusDays(1).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
    val end = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
    val apps = sm.queryAndAggregateUsageStats(start,end).keys.filter {
        it.contains("apk") || it.contains("qq")
    }

    apps.subList(0,1).forEachIndexed { index, packageInfo ->
        val d = context.getAppIcon(packageInfo)
        val w = d.intrinsicWidth
        val h = d.intrinsicHeight
        val bitmap = Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        d.setBounds(0,0,w,h)
        d.draw(canvas)
        views.setImageViewBitmap(R.id.weight_app_first, bitmap)
        val intent = Intent(CUSTOM_INTENT_ACTION_WIDGET_EVENT).putExtra(
            "packageName",packageInfo
        ).setPackage(context.packageName)
        val pendingIntent = PendingIntent.getBroadcast(context,1,intent,PendingIntent.FLAG_IMMUTABLE)
        views.setOnClickPendingIntent(R.id.weight_app_first,pendingIntent)
    }

    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(appWidgetId, views)
}